package com.example.sms_listener

import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.util.Log

/**
 * 短信帮助类
 * 
 * 提供读取和操作短信数据的工具方法
 */
object SmsHelper {
    
    private const val TAG = "SmsHelper"
    
    /// 短信内容URI
    private val SMS_URI = Uri.parse("content://sms/")
    
    /// 收件箱URI
    private val INBOX_URI = Uri.parse("content://sms/inbox")
    
    /// 发件箱URI  
    private val SENT_URI = Uri.parse("content://sms/sent")

    /**
     * 获取最后一条短信
     */
    fun getLastSms(context: Context): Map<String, Any>? {
        var cursor: Cursor? = null
        try {
            // 查询最新的一条短信
            cursor = context.contentResolver.query(
                SMS_URI,
                arrayOf("_id", "address", "body", "date", "type"),
                null,
                null,
                "date DESC LIMIT 1"
            )
            
            if (cursor != null && cursor.moveToFirst()) {
                return extractSmsFromCursor(cursor)
            }
            
        } catch (e: SecurityException) {
            Log.e(TAG, "没有权限读取短信", e)
        } catch (e: Exception) {
            Log.e(TAG, "获取最后一条短信时发生错误", e)
        } finally {
            cursor?.close()
        }
        
        return null
    }

    /**
     * 获取短信历史记录
     */
    fun getSmsHistory(context: Context, limit: Int, offset: Int): List<Map<String, Any>> {
        val smsList = mutableListOf<Map<String, Any>>()
        var cursor: Cursor? = null
        
        try {
            // 查询短信，按时间倒序排列
            cursor = context.contentResolver.query(
                SMS_URI,
                arrayOf("_id", "address", "body", "date", "type"),
                null,
                null,
                "date DESC LIMIT $limit OFFSET $offset"
            )
            
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    val smsData = extractSmsFromCursor(cursor)
                    if (smsData != null) {
                        smsList.add(smsData)
                    }
                }
            }
            
        } catch (e: SecurityException) {
            Log.e(TAG, "没有权限读取短信", e)
        } catch (e: Exception) {
            Log.e(TAG, "获取短信历史记录时发生错误", e)
        } finally {
            cursor?.close()
        }
        
        return smsList
    }

    /**
     * 从Cursor中提取短信数据
     */
    private fun extractSmsFromCursor(cursor: Cursor): Map<String, Any>? {
        try {
            val idIndex = cursor.getColumnIndex("_id")
            val addressIndex = cursor.getColumnIndex("address")
            val bodyIndex = cursor.getColumnIndex("body")
            val dateIndex = cursor.getColumnIndex("date")
            val typeIndex = cursor.getColumnIndex("type")
            
            // 检查列索引是否有效
            if (addressIndex == -1 || bodyIndex == -1 || dateIndex == -1 || typeIndex == -1) {
                Log.w(TAG, "短信数据列索引无效")
                return null
            }
            
            val id = if (idIndex != -1) cursor.getLong(idIndex) else 0L
            val address = cursor.getString(addressIndex) ?: ""
            val body = cursor.getString(bodyIndex) ?: ""
            val date = cursor.getLong(dateIndex)
            val type = cursor.getInt(typeIndex)
            
            return mapOf(
                "id" to id,
                "address" to address,
                "body" to body,
                "date" to date,
                "type" to type
            )
            
        } catch (e: Exception) {
            Log.e(TAG, "提取短信数据时发生错误", e)
            return null
        }
    }

    /**
     * 根据发送者获取短信
     */
    fun getSmsByAddress(context: Context, address: String, limit: Int = 10): List<Map<String, Any>> {
        val smsList = mutableListOf<Map<String, Any>>()
        var cursor: Cursor? = null
        
        try {
            cursor = context.contentResolver.query(
                SMS_URI,
                arrayOf("_id", "address", "body", "date", "type"),
                "address = ?",
                arrayOf(address),
                "date DESC LIMIT $limit"
            )
            
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    val smsData = extractSmsFromCursor(cursor)
                    if (smsData != null) {
                        smsList.add(smsData)
                    }
                }
            }
            
        } catch (e: SecurityException) {
            Log.e(TAG, "没有权限读取短信", e)
        } catch (e: Exception) {
            Log.e(TAG, "根据发送者获取短信时发生错误", e)
        } finally {
            cursor?.close()
        }
        
        return smsList
    }

    /**
     * 根据关键词搜索短信
     */
    fun searchSms(context: Context, keyword: String, limit: Int = 20): List<Map<String, Any>> {
        val smsList = mutableListOf<Map<String, Any>>()
        var cursor: Cursor? = null
        
        try {
            cursor = context.contentResolver.query(
                SMS_URI,
                arrayOf("_id", "address", "body", "date", "type"),
                "body LIKE ?",
                arrayOf("%$keyword%"),
                "date DESC LIMIT $limit"
            )
            
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    val smsData = extractSmsFromCursor(cursor)
                    if (smsData != null) {
                        smsList.add(smsData)
                    }
                }
            }
            
        } catch (e: SecurityException) {
            Log.e(TAG, "没有权限读取短信", e)
        } catch (e: Exception) {
            Log.e(TAG, "搜索短信时发生错误", e)
        } finally {
            cursor?.close()
        }
        
        return smsList
    }

    /**
     * 获取收件箱短信数量
     */
    fun getInboxSmsCount(context: Context): Int {
        var cursor: Cursor? = null
        try {
            cursor = context.contentResolver.query(
                INBOX_URI,
                arrayOf("COUNT(*)"),
                null,
                null,
                null
            )
            
            if (cursor != null && cursor.moveToFirst()) {
                return cursor.getInt(0)
            }
            
        } catch (e: SecurityException) {
            Log.e(TAG, "没有权限读取短信", e)
        } catch (e: Exception) {
            Log.e(TAG, "获取收件箱短信数量时发生错误", e)
        } finally {
            cursor?.close()
        }
        
        return 0
    }

    /**
     * 获取未读短信数量
     */
    fun getUnreadSmsCount(context: Context): Int {
        var cursor: Cursor? = null
        try {
            cursor = context.contentResolver.query(
                INBOX_URI,
                arrayOf("COUNT(*)"),
                "read = 0",
                null,
                null
            )
            
            if (cursor != null && cursor.moveToFirst()) {
                return cursor.getInt(0)
            }
            
        } catch (e: SecurityException) {
            Log.e(TAG, "没有权限读取短信", e)
        } catch (e: Exception) {
            Log.e(TAG, "获取未读短信数量时发生错误", e)
        } finally {
            cursor?.close()
        }
        
        return 0
    }

    /**
     * 检查是否有短信权限
     */
    fun hasSmsPermission(context: Context): Boolean {
        return try {
            // 尝试查询一条短信来验证权限
            val cursor = context.contentResolver.query(
                SMS_URI,
                arrayOf("_id"),
                null,
                null,
                "LIMIT 1"
            )
            cursor?.close()
            true
        } catch (e: SecurityException) {
            false
        } catch (e: Exception) {
            Log.e(TAG, "检查短信权限时发生错误", e)
            false
        }
    }
} 